<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Admin;

use App\Request\RoleRequest;
use App\Service\AdminRoleService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\PutMapping;
use Psr\Http\Message\ResponseInterface;

/**
 * 角色
 * Class RoleController.
 */
#[Controller(prefix: 'admin/role')]
class RoleController extends MainController
{
    #[Inject]
    protected AdminRoleService $adminRoleService;

    /**
     * 角色集合.
     */
    #[GetMapping('roles')]
    public function roles(): ResponseInterface
    {
        $data = $this->adminRoleService->roles();
        return $this->success($data);
    }

    /**
     * 角色列表.
     */
    #[GetMapping('roleList')]
    public function roleList(): ResponseInterface
    {
        return $this->success(
            $this->adminRoleService->getRoleList($this->request->all())
        );
    }

    /**
     * 新增.
     */
    #[PostMapping('create')]
    public function create(RoleRequest $request): ResponseInterface
    {
        // php bin/hyperf.php gen:request RoleRequest
        $data = $request->inputs(['name', 'desc', 'status']);

        if ($this->adminRoleService->save($data) >= 1) {
            return $this->success();
        }

        return $this->error();
    }

    /**
     * 更新.
     */
    #[PutMapping('update/{id}')]
    public function update(int $id, RoleRequest $request): ResponseInterface
    {
        $data = $request->inputs(['name', 'desc', 'status']);

        if ($this->adminRoleService->update($id, $data)) {
            return $this->success();
        }
        return $this->error();
    }

    /**
     * 删除.
     */
    #[DeleteMapping('delete/{id}')]
    public function delete(int $id): ResponseInterface
    {
        $this->adminRoleService->delete((array)$id);
        return $this->success();
    }

    /**
     * 设置权限.
     */
    #[PostMapping('setRules/{id}')]
    public function setRules(int $id): ResponseInterface
    {
        $data = $this->request->input('rule_ids');
        $this->adminRoleService->setRules($data, $id);
        return $this->success();
    }
}
